/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
Ext.onReady(function() {
    var paper_id = -1;
    var area_id = -1;
    var ds = new Ext.data.GroupingStore({
        remoteSort: true,
        groupField: 'area_short',
        sortInfo: {
            field: 'id',
            direction: 'ASC'
        },
        proxy: new Ext.data.HttpProxy({
            url: 'admin/getpapers'
        }),
        reader: new Ext.data.JsonReader({
            root: 'papers',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'title'
        },
        {
            name: 'authors'
        },
        {
            name: 'abstract'
        },
        {
            name: 'date_sent'
        },
        {
            name: 'isAccepted',
            type: 'bool'
        },
        {
            name: 'isActive',
            type: 'bool'
        },
        {
            name: 'file_pdf'
        },
        {
            name: 'file_doc'
        },
        {
            name: 'file_size_pdf'
        },
        {
            name: 'file_size_doc'
        },
        {
            name: 'category_id'
        },
        {
            name: 'area_id'
        },
        {
            name: 'area_short'
        },
        {
            name: 'email'
        }])
    });
    var a_store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'area/all'
        }),
        reader: new Ext.data.JsonReader({
            root: 'areas',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'name_en'
        },
        {
            name: 'name_mk'
        },
        {
            name: 'short'
        },
        {
            name: 'description'
        }])
    });
    var c_store = new Ext.data.Store({
        remoteSort: true,
        sortInfo: {
            field: 'name_en',
            direction: 'ASC'
        },
        proxy: new Ext.data.HttpProxy({
            url: 'category/byArea'
        }),
        reader: new Ext.data.JsonReader({
            root: 'categories',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'name_mk'
        },
        {
            name: 'name_en'
        },
        {
            name: 'description',
            mapping: 'description'
        }])
    });
    var filters = new Ext.ux.grid.GridFilters({
        filters: [{
            type: 'string',
            dataIndex: 'title'
        },
        {
            type: 'string',
            dataIndex: 'authors'
        },
        {
            type: 'string',
            dataIndex: 'category_name'
        },
        {
            type: 'string',
            dataIndex: 'area_name'
        }]
    });
    /*    var pagingBar = new Ext.PagingToolbar({
        pageSize: 25,
        store: ds,
        displayInfo: true,
        displayMsg: 'Displaying papers {0} - {1} of {2}',
        emptyMsg: "No papers to display"
    });*/
    function renderReviewer(value, p, r) {
        var yes = '<img src="../images/2.jpg">';
        var no = '<img src="../images/1.jpg">';
        if (value) {
            return yes;
        } else {
            return no;
        }
    }
    function renderDownload(value, p, r) {
        var str = '';
        var img_pdf = '<img src="../images/pdf.png">&nbsp;';
        var img_doc = '<img src="../images/doc.png">&nbsp;';
        var pdf = r.data['file_pdf'];
        var doc = r.data['file_doc'];
        if (pdf != '') {
            str += String.format('<div><a href="paper/download/?id={0}&ft=pdf">{2}</a><a href="paper/download/?id={0}&ft=pdf">{1}</a> {3} KB</div>', value, pdf, img_pdf, r.data['file_size_pdf']);
        }
        if (doc != '') {
            str += String.format('<div><a href="paper/download/?id={0}&ft=doc">{2}</a><a href="paper/download/?id={0}&ft=doc">{1}</a> {3} KB</div>', value, doc, img_doc, r.data['file_size_doc']);
        }
        return str;
    }
    var exportAction = function() {        
        window.location = 'export/papers';        
    }
    // create the grid
    var grid = new Ext.grid.GridPanel({
        store: ds,
        columns: [{
            header: "Title",
            width: 280,
            dataIndex: 'title',
            sortable: true
        },
        {
            header: "Date Sent",
            width: 120,
            dataIndex: 'date_sent',
            sortable: true
        },
        {
            header: "Area",
            width: 50,
            dataIndex: 'area_short',
            sortable: true
        },
        {
            header: "Files",
            width: 120,
            dataIndex: 'id',
            sortable: true,
            renderer: renderDownload
        }],
        view: new Ext.grid.GroupingView({            
            hideGroupedColumn: true,
            startCollapsed: true,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Papers" : "Paper"]})'
        }),
        tbar: [{
            text: 'Export',
            handler: exportAction,
            waitMsg: 'Exporting participants...',
            tooltip: 'Click to export participants to xls'
        }],
        plugins: filters,
        renderTo: 'data-grid',
        width: 550,
        height: 480,
        title: 'Papers',
        frame: true,
        loadMask: true
    });
    grid.on('rowclick',
    function(grid, rowIndex, e) {
        var record = ds.getAt(rowIndex);
        paper_id = record.id;
        var a_id = record.get('area_id');
        var c_id = record.get('category_id');
        if (a_id != area_id) {
            c_store.load({
                params: {
                    area_id: a_id
                },
                callback: function(r, options, success) {
                    paperForm.getForm().loadRecord(record);
                }
            });
            area_id = a_id;
        } else {
            paperForm.getForm().loadRecord(record);
        }
        id = record.get('id');
    });
    var c_combo = new Ext.form.ComboBox({
        fieldLabel: lbl_topic,
        hiddenName: 'category_id',
        id: 'cid',
        store: c_store,
        valueField: 'id',
        displayField: 'name_' + lang,
        typeAhead: true,
        mode: 'local',
        emptyText: lbl_select_topic,
        editable: false,
        selectOnFocus: true,
        triggerAction: 'all',
        forseSelection: true,
        allowBlank: false,
        blankText: msg_blank,
        width: 190
    });
    var paperForm = new Ext.FormPanel({
        id: 'paperForm',
        renderTo: 'paper-form',
        frame: true,
        title: lbl_panel_title,
        bodyStyle: 'padding:5px 5px 0',
        labelAlign: 'right',
        width: 480,
        height: 480,
        waitMsgTarget: true,
        items: [{
            xtype: 'fieldset',
            id: 'fsLogin',
            title: lbl_form_title,
            defaults: {
                width: 300
            },
            defaultType: 'textfield',
            height: 340,
            width: 460,
            labelWidth: 120,
            items: [{
                fieldLabel: lbl_title,
                name: 'title',
                readOnly: true,
                blankText: msg_blank,
                allowBlank: false
            },
            new Ext.form.TextArea({
                fieldLabel: lbl_authors,
                id: 'authors',
                name: 'authors',
                readOnly: true,
                blankText: msg_blank,
                allowBlank: false
            }), new Ext.form.TextArea({
                fieldLabel: lbl_abstract,
                name: 'abstract',
                readOnly: true,
                blankText: msg_blank,
                allowBlank: false
            }), new Ext.form.ComboBox({
                fieldLabel: lbl_area,
                hiddenName: 'area_id',
                id: 'aid',
                store: a_store,
                valueField: 'id',
                displayField: 'name_' + lang,
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText: lbl_select_area,
                selectOnFocus: true,
                forseSelection: true,
                editable: false,
                allowBlank: false,
                blankText: msg_blank,
                width: 190,
                onSelect: function(record) {
                    c_store.load({
                        params: {
                            area_id: record.data.id
                        }
                    });
                    c_combo.setValue('');
                    area_short = record.data['short'];
                    this.setValue(record.data[this.valueField || this.displayField]);
                    this.collapse();
                }
            }), c_combo, {
                fieldLabel: lbl_corespondence,
                id: 'email',
                name: 'email',
                readOnly: true,
                blankText: msg_blank,
                vtype: 'email',
                allowBlank: false
            },
            {
                xtype: 'checkbox',
                fieldLabel: 'Is Active',
                name: 'isActive',
                id: 'isActive'
            }],
            buttons: [{
                text: lbl_button,
                type: 'submit',
                name: 'regsbmt',
                handler: function() {
                    var form = paperForm.getForm();
                    if (form.isValid()) {
                        form.submit({
                            params: {
                                id: paper_id
                            },
                            url: 'admin/updatepaper',
                            waitMsg: msg_wait,
                            success: updateComplete
                        });
                    }
                }
            }]
        }]
    });
    a_store.load();
    ds.load();
    var updateComplete = function(form, action) {
        Ext.Msg.alert("Status", "Changes saved succussfully.");
        ds.load();
    }
});